import {
  HttpException,
  HttpStatus,
  Inject,
  Injectable,
  Logger,
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from 'src/prisma/prisma.service';
import { RegisterUserDto } from './dto/register-user.dto';
import { RedisService } from 'src/redis/redis.service';
import { LoginUserDto } from './dto/login-user.dto';
import { JwtService } from '@nestjs/jwt';
import { UpdateUserPasswordDto } from './dto/update-password.dto';
import { UpdateUserDto } from './dto/udpate-user.dto';

@Injectable()
export class UserService {
  @Inject(PrismaService)
  private prismaService: PrismaService;

  @Inject(JwtService)
  private jwtService: JwtService;

  private logger = new Logger();

  @Inject(RedisService)
  private redisService: RedisService;

  create(data: Prisma.UserCreateInput) {
    return this.prismaService.user.create({
      data,
      select: {
        id: true,
      },
    });
  }

  async register(user: RegisterUserDto) {
    // const storeCaptcha = await this.redisService.get(`captcha_${user.email}`);
    // if (!storeCaptcha) {
    //   throw new HttpException('验证码已失效', HttpStatus.BAD_REQUEST);
    // }
    // if (storeCaptcha !== user.captcha) {
    //   throw new HttpException('验证码不正确', HttpStatus.BAD_REQUEST);
    // }

    const foundUser = await this.prismaService.user.findUnique({
      where: {
        username: user.username,
      },
    });
    if (foundUser) {
      throw new HttpException('用户已存在', HttpStatus.BAD_REQUEST);
    }

    try {
      return await this.prismaService.user.create({
        data: {
          username: user.username,
          password: user.password,
          nickName: user.nickName,
          email: user.email,
        },
        select: {
          id: true,
          username: true,
          nickName: true,
          email: true,
          headPic: true,
          createTime: true,
        },
      });
    } catch (error) {
      this.logger.error(error, UserService);
      return null;
    }
  }

  async login(loginUser: LoginUserDto) {
    const user = await this.prismaService.user.findUnique({
      where: {
        username: loginUser.username,
      },
    });

    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }

    if (user.password !== loginUser.password) {
      throw new HttpException('密码错误', HttpStatus.BAD_REQUEST);
    }

    delete user.password;

    const vo = {
      user,
      token: this.jwtService.sign(
        {
          userId: user.id,
          username: user.username,
        },
        {
          expiresIn: `7d`,
        },
      ),
    };

    return vo;
  }

  async findUserDetailById(userId: number) {
    const user = await this.prismaService.user.findUnique({
      where: {
        id: userId,
      },
      select: {
        id: true,
        username: true,
        nickName: true,
        email: true,
        headPic: true,
        createTime: true,
      },
    });

    return user;
  }

  async updatePassword(passwordDto: UpdateUserPasswordDto, userInfo: any) {
    const user = await this.prismaService.user.findUnique({
      where: {
        id: userInfo.userId,
      },
    });
    const captcha = await this.redisService.get(
      `update_password_captcha_${user.email}`,
    );

    if (!captcha) {
      throw new HttpException(`验证码已失效`, HttpStatus.BAD_REQUEST);
    }

    if (captcha !== passwordDto.captcha) {
      throw new HttpException(`验证码不正确`, HttpStatus.BAD_REQUEST);
    }

    try {
      await this.prismaService.user.update({
        where: {
          id: userInfo.userId,
        },
        data: {
          password: passwordDto.password,
        },
      });
      return '密码修改成功';
    } catch (error) {
      this.logger.error(error, UserService);
      return '密码修改失败';
    }
  }

  async update(userId, updateUserDto: UpdateUserDto) {
    const foundUser = await this.prismaService.user.findUnique({
      where: {
        id: userId,
      },
    });

    if (updateUserDto.nickName) {
      foundUser.nickName = updateUserDto.nickName;
    }
    if (updateUserDto.headPic) {
      foundUser.headPic = updateUserDto.headPic;
    }

    try {
      await this.prismaService.user.update({
        where: {
          id: userId,
        },
        data: foundUser,
      });

      return `success`;
    } catch (error) {
      this.logger.error(error, UserService);
      return 'error';
    }

    // return foundUser;
  }

  
}
